
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <getopt.h>
#include <stdio.h>
#include "can_rx.h"

struct can_frame receive_can_message(const char *ifname)
{
    int                     fd;
    struct sockaddr_can     addr;
    struct ifreq            ifr;
    struct can_frame        frame;

    // 创建socket
    fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (fd < 0) {
        perror("socket");
        exit(1);
    }

    // 指定CAN接口
    strcpy(ifr.ifr_name, ifname);
    ioctl(fd, SIOCGIFINDEX, &ifr);
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;

    // 绑定socket到CAN接口
    if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("bind");
        exit(1);
    }

    // 接收CAN帧
    int nbytes = read(fd, &frame, sizeof(struct can_frame));
    if (nbytes < 0)
    {
        perror("read");
        exit(1);
    }

    if (nbytes < sizeof(struct can_frame))
    {
        fprintf(stderr, "read: incomplete CAN frame\n");
        exit(1);
    }

    // 关闭socket
    close(fd);

    // 返回接收到的CAN帧数据
    return frame;
}
